package com.acc.store.contorller;

import com.acc.store.common.Result;
import com.acc.store.dto.UserDto;
import com.acc.store.entity.User;
import com.acc.store.service.UserService;
import com.acc.store.vo.UserVo;
import com.baomidou.mybatisplus.core.metadata.IPage;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
@Tag(name = "用户操作")
//@Api(tags = "用户操作")
public class UserController {

    @Autowired
    UserService userService;

    @DeleteMapping("/delete/{id}")
    @Operation(summary = "删除用户")
    public Result delete(@PathVariable Long id) {
        userService.removeById(id);
        return Result.success(null);
    }

    @PostMapping("/save")
    @Operation(summary = "保存用户")
    public Result save(@RequestBody User user) {
        Long l = userService.saveInfo(user);
        return Result.success(l);
    }

    @Operation(summary = "更新用户")
    @PutMapping("/update")
    public Result update(@RequestBody User user) {
        userService.updateById(user);
        return Result.success(null);
    }

    private final Map<Object, Integer> userLock = new HashMap<>();

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result login(@RequestBody UserDto userDto) {
        UserVo userVo = null;
        // 检查用户是否被锁定
        Integer loginAttempts = userLock.getOrDefault(userDto, 0);
        if (loginAttempts >= 3) {
            return Result.error("账户已被锁定，请联系管理员解锁");
        }
        userVo = userService.login(userDto);
        if (userVo == null) {
            // 记录用户登录失败次数
            userLock.put(userDto, loginAttempts + 1);
            if (loginAttempts + 1 >= 3) {
                // 锁定用户
                userLock.put(userDto, 3);
                return Result.error("密码错误，账户已被锁定，请联系管理员解锁");
            }
            return Result.error("密码错误");
        }
        // 登录成功清除用户锁定计数
        userLock.remove(userDto);
        return Result.success(userVo);
    }

    @Operation(summary = "用户分页")
    @GetMapping("/list")
    public Result getUsers(@RequestParam Map<String, Object> params) {
        IPage<User> page = userService.getPage(params);
        return Result.success(page);
    }
    @Operation(summary = "用户列表")
    @GetMapping("/list/all")
    public Result getUsers() {
        List<User> userList = userService.list();
        return Result.success(userList);
    }

    @Operation(summary = "获取用户信息")
    @GetMapping("/get/{id}")
    public Result getById(@PathVariable Long id) {
        User byId = userService.getById(id);
        return Result.success(byId);
    }
}
